package me.suntao.javaio.server.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class Nio2EchoServerHandler implements Runnable {
  private int port;
  CountDownLatch latch;
  AsynchronousServerSocketChannel socketChannel;

  public Nio2EchoServerHandler(int port) {
    this.port = port;
    //获取AsynchronousServerSocketChannel对象
    try {
      socketChannel=AsynchronousServerSocketChannel.open();
      //绑定服务端口
      socketChannel.bind(new InetSocketAddress(this.port));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override public void run() {
    latch = new CountDownLatch(1);
    doAccept();
    try {
      latch.await();
    }catch (InterruptedException ex){
      ex.printStackTrace();
    }
  }

  /**
   * 接受客户单连接
   */
  public void doAccept(){
    socketChannel.accept(this,new AcceptCompletionHandler());
  }
}
